﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 控制台应用
{
    public class DateTimeConver
    {
        public string dateTime1 = "2021-5-6";
        public string dateTime2 = "2021/5/6";

        #region 获取一个日期的前一天
        /// <summary>
        /// 获取一个日期的前一天
        /// </summary>
        /// <param name="dateTime">日期字符串</param>
        /// <param name="dateFormat">返回的日期字符串格式</param>
        /// <returns>日期字符串</returns>
        public string getBeforeDate(string dateTime, string dateFormat)
        {
            try
            {
                return Convert.ToDateTime(dateTime).AddDays(-1).ToString(dateFormat);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region 获取一个日期的后一天
        /// <summary>
        /// 获取一个日期的前一天
        /// </summary>
        /// <param name="dateTime">日期字符串</param>
        /// <param name="dateFormat">返回的日期字符串格式</param>
        /// <returns>日期字符串</returns>
        public string getAfterDate(string dateTime, string dateFormat)
        {
            try
            {
                return Convert.ToDateTime(dateTime).AddDays(1).ToString(dateFormat);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region 获取一个月有多少天
        /// <summary>
        /// 获取一个月有多少天
        /// </summary>
        /// <param name="strDateTime">日期字符串</param>
        /// <returns></returns>
        public int getDaysInMonth(string strDateTime)
        {
            try
            {
                DateTime date = Convert.ToDateTime(strDateTime);
                int year = date.Year;
                int month = date.Month;
                int days = DateTime.DaysInMonth(year, month);
                return days;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        #endregion

    }
}
